package com.xuecheng.checkcode.service.impl;

import com.xuecheng.checkcode.service.IEmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @author 勾新杰
 * @version 1.0
 * @description:
 * @date 2025/3/9 22:55
 */
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements IEmailService {

    private final JavaMailSender mailSender;

    private final MailProperties mailProperties;

    /**
     * 发送邮件
     *
     * @param destination 接收人邮箱
     * @param subject     邮件主题
     * @param content     邮件内容
     * @param isHtml      是否为html格式
     */
    @Override
    public boolean sendEmail(String destination, String subject, String content, boolean isHtml) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            // 防止被当成垃圾邮件
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(mailProperties.getUsername(), "51xuecheng.com");
            helper.setTo(destination);
            helper.setSubject(subject);
            helper.setText(content, isHtml); // 第二个参数由外部控制是否为 HTML
            mailSender.send(message);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            return false;
        }
    }
}
